<template>
  <div class="update-photo">
    <img :src="srcAddress" class="img" ref="imgRef" />
    <div class="toolbar">
      <div class="cancel" @click="$emit('close')">取消</div>
      <div class="over" @click="overBtn">完成</div>
    </div>
  </div>
</template>

<script>
import Cropper from 'cropperjs'
import 'cropperjs/dist/cropper.css'
import { updateUserPhoto } from '@/api/user.js'
export default {
  name: 'updatePhoto',
  data() {
    return {
      cropper: null
    }
  },
  props: {
    srcAddress: {
      type: [String, Object],
      required: true
    }
  },
  mounted() {
    const image = this.$refs.imgRef
    this.cropper = new Cropper(image, {
      viewMode: 1,
      dragMode: 'move',
      aspectRatio: 1,
      autoCropArea: 1,
      cropBoxMovable: false,
      cropBoxResizable: false,
      background: false,
      movable: true
    })
  },
  methods: {
    overBtn() {
      this.cropper.getCroppedCanvas().toBlob(async blob => {
        // loading状态圈圈
        this.$toast.loading({
          message: '上传中...',
          forbidClick: true, // 禁止背景点击
          duration: 0 // 持续展示
        })
        try {
          const formData = new FormData()
          formData.append('photo', blob)
          const { data } = await updateUserPhoto(formData)
          // 关闭弹出层
          this.$emit('close')
          // 更新视图
          this.$emit('updatephoto', data.data.photo)
          this.$toast.success('上传成功')
        } catch (err) {
          this.$toast('上传失败，请重试')
        }
      })
    }
  }
}
</script>

<style scoped lang="less">
.update-photo {
  background-color: #000;
  height: 100%;
  .img {
    max-width: 100%;
    display: block;
  }
  .toolbar {
    position: fixed;
    bottom: 0;
    right: 0;
    left: 0;
    display: flex;
    justify-content: space-between;
    .cancel,
    .over {
      width: 90px;
      height: 90px;
      font-size: 30px;
      display: flex;
      justify-content: center;
      align-items: center;
      color: #fff;
    }
  }
}
</style>
